package com.leilei.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.leilei.entity.*;
import com.leilei.service.ICommodityService;
import com.leilei.service.IShopCartService;
import com.leilei.service.impl.CommodityServiceImpl;
import com.leilei.service.impl.ShopCartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ShoppingCartServlet")
public class ShoppingCartServlet extends BaseServlet{

    private ICommodityService commodityService = new CommodityServiceImpl();
    private IShopCartService shopCartService = new ShopCartServiceImpl();

    public ShoppingCartServlet(){

    }

    protected void shoppingCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取到要购买的商品的id
        String spid = req.getParameter("pid");
        String spvid = req.getParameter("pvid");
        String spcid = req.getParameter("pcid");

        int pid = spid == null ? 0 : Integer.parseInt(spid);
        int pvid = spvid == null ? 0 : Integer.parseInt(spvid);
        int pcid = spcid == null ? 0 : Integer.parseInt(spcid);

        //根据id查找商品的信息
        Commodity commodity = commodityService.getCommodityCustom(pid, pvid, pcid);

        //获取session中的购物车
        HttpSession session = req.getSession();
        Object cart = session.getAttribute("cart");
        User user = (User) session.getAttribute("user");

        //实例化 购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUser(user);
        shoppingCart.setCommodity(commodity);
        shoppingCart.setCount(1);
        //实例化定制信息
        ShoppingCustom shoppingCustom = new ShoppingCustom();
        shoppingCustom.setPid(pid);
        shoppingCustom.setPvid(pvid);
        shoppingCustom.setPcid(pcid);

        Map<ShoppingCustom, ShoppingCart> mapcart = null;

        //如果session中的购物车为空，则新建购物车集合
        if (cart == null){

            mapcart = new HashMap<>();
            mapcart.put(shoppingCustom, shoppingCart);
            //设置session中的购物车
            session.setAttribute("cart", mapcart);

        }else {

            mapcart = (Map<ShoppingCustom, ShoppingCart>) cart;
            //该型号是否已经存在
            if (mapcart.containsKey(shoppingCustom)){
                //存在则count加一
                ShoppingCart s = mapcart.get(shoppingCustom);
                s.setCount(s.getCount() + 1);
                //放置修改后的商品
                mapcart.put(shoppingCustom, s);

                session.setAttribute("cart", mapcart);
            } else{

                mapcart.put(shoppingCustom, shoppingCart);

                session.setAttribute("cart", mapcart);
            }

        }

    }

    protected void saveShopCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取session中的购物车、购买的商品
        HttpSession session = req.getSession();
        Map<ShoppingCustom, ShoppingCart> cart = (Map<ShoppingCustom, ShoppingCart>) session.getAttribute("cart");
        User user = (User) session.getAttribute("user");
        Map<ShoppingCountCustom, Commodity> map = (Map<ShoppingCountCustom, Commodity>)session.getAttribute("cdmap");

        Map<ShoppingCustom, ShoppingCart> buyMap = new HashMap<>();
        //遍历购买的商品
        for (ShoppingCountCustom shoppingCountCustom : map.keySet()) {

            //完善value的信息
            Commodity commodity = map.get(shoppingCountCustom);
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setIsbuy(1);
            shoppingCart.setCount(shoppingCountCustom.getCount());
            shoppingCart.setUser(user);
            shoppingCart.setCommodity(commodity);

            //实例化一个购买的购物车key
            ShoppingCustom sc = new ShoppingCustom();
            sc.setPid(shoppingCountCustom.getPid());
            sc.setPcid(shoppingCountCustom.getPcid());
            sc.setPvid(shoppingCountCustom.getPvid());

            //移除临时购物车中已买的商品
            cart.remove(sc);

            buyMap.put(sc, shoppingCart);
        }

        //保存已买信息
        boolean result = shopCartService.saveShopCart(buyMap);

        //返回购物车页面
        session.setAttribute("cart", cart);
        req.getRequestDispatcher("/jsp/shoppingCustom.jsp").forward(req, resp);

    }

    protected void shopCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String json = req.getParameter("json");

        ObjectMapper mapper = new ObjectMapper();
        ArrayList<ShoppingCountCustom> list = mapper.readValue(json, new TypeReference<ArrayList<ShoppingCountCustom>>(){});

        int sumshop = 0;
        //设置购物车
        Map<ShoppingCountCustom, Commodity> commodityMap = new HashMap<>();
        for (ShoppingCountCustom shoppingCountCustom : list) {

            if (shoppingCountCustom.getPid() != 0){
                //根据id查找商品的信息
                Commodity commodity = commodityService.getCommodityCustom(shoppingCountCustom.getPid(),
                        shoppingCountCustom.getPvid(),
                        shoppingCountCustom.getPcid());
                commodityMap.put(shoppingCountCustom, commodity);

                sumshop += commodity.getCommodityVersion().get(0).getOprice() * shoppingCountCustom.getCount();
            }

        }

        HttpSession session = req.getSession();
        session.setAttribute("cdmap", commodityMap);
        session.setAttribute("sumshop", sumshop);

        resp.getWriter().write("jiesuan.jsp");

    }

}
